﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using MyMoviesBrowserLibrary.MyMovies;

using Microsoft.MediaCenter.UI;

namespace MyMoviesBrowser
{
    public class MyMovie
    {
        string[] extensions = new string[] { "*.mov", "*.avi", "*.mpeg", "*.mpg", "*.mkv", "*.wmv", "*.mp4", "*.dvr-ms", "*.m2ts", "*.ts" };
        public Title MovieTitle { get; set; }
        private List<Person> persons { get; set; }
        private List<Studio> studios { get; set; }
        private List<Genre> genres { get; set; }
        private List<Category> categories { get; set; }
        private BooleanChoice _checkBoxItem = new BooleanChoice();

        public string Title { get { return MovieTitle.OriginalTitle; } }
        public string SortTitle { get { return MovieTitle.SortTitle; } }
        public string Runtime
        {
            get
            {
                if (MovieTitle.intRuntime.HasValue)
                {
                    TimeSpan span = TimeSpan.FromMinutes(MovieTitle.intRuntime.Value);
                    return string.Format("{0}h {1}m", span.Hours, span.Minutes);
                }
                else
                    return "";
            }
        }
        public string Studio
        {
            get
            {
                if (studios == null)
                    return "";
                else
                    return string.Join(",", studios.Select(s => s.nvcName).ToArray());
            }
        }
        public string Rating 
        { 
            get 
            {
                string[] ratings = new string[] { "", "Not Rated", "G", "PG", "PG-13", "NC-17", "R" };
                if (MovieTitle.intCertification.HasValue && MovieTitle.intCertification < ratings.Length && MovieTitle.intCertification >= 0)
                    return ratings[MovieTitle.intCertification.Value];
                return "";
            } 
        }
        public string MovieDescription { get { return MovieTitle.Description; } }
        public string Genre
        {
            get
            {
                if (genres == null)
                    return "";
                else
                    return string.Join(",", genres.Select(s => s.nvcName).ToArray());
            }
        }
        public string MovieDirectory
        {
            get
            {
                return MovieTitle.MovieDirectory;
            }
        }
        public string FolderImage { get; set; }
        public bool ShowBackgroundImage
        {
            get
            {
                string imageLocation = Path.Combine(MovieDirectory, "fanart.jpg");
                return File.Exists(imageLocation);
            }
        }
        public Image BackgroundImage
        {
            get
            {
                string imageLocation = Path.Combine(MovieDirectory, "fanart.jpg");
                if (File.Exists(imageLocation))
                    return new Image("file://" + imageLocation);
                else
                    return new Image("resx://MyMoviesBrowser/MyMoviesBrowser.Resources/clear");
            }
        }
        public DateTime? ReleaseDate { get { return MovieTitle.datDVDRelease; } }
        public string FrontCover { get { return FolderImage; } }
        public string BackCover { get; set; }
        public string RatingDescription
        {
            get
            {
                return MovieTitle.nvcCertificationCause;
            }
        }
        public string Director { get; set; }

        public Image Image { get; set; }

        public List<MediaFile> Files { get; set; }
        public List<CastMember> Cast { get; set; }

        public BooleanChoice CheckBoxItem { get; set; }
        public BooleanChoice WatchTrailersCheckBoxItem { get; set; }
        public Choice SpinnerItems { get; set; }

        public int NumberOfTrailersToPlay { get; set; }


        void CheckBoxItem_PropertyChanged(IPropertyObject sender, string property)
        {
            if (property == "Value")
            {
                MovieTitle.Watched = CheckBoxItem.Value;
            }
        }

        public MyMovie()             
        {
            Cast = new List<CastMember>();
            //Files = new List<MediaFile>();
            CheckBoxItem = new BooleanChoice();
            WatchTrailersCheckBoxItem = new BooleanChoice();

            CheckBoxItem.Description = "Watched";

            WatchTrailersCheckBoxItem.Description = "Watch Previews";
            WatchTrailersCheckBoxItem.Value = false;


            SpinnerItems = new Choice();
            List<string> stringItems = new List<string>() { "0", "1", "2", "3", "4", "5", "6" };
            SpinnerItems.Options = stringItems;
            SpinnerItems.ChosenChanged += new EventHandler(SpinnerItems_ChosenChanged);
        }

        public MyMovie(Title title, string serverName)
            : this()
        {
            MovieTitle = title;
            MyMoviesDataContext ctx = MyMoviesBusiness.GetNewMyMoviesDataContext();

            genres = (from tg in ctx.TitleGenres
                    join g in ctx.Genres on tg.intGenre equals g.intId
                    where tg.intTitle == title.intId
                    select g).ToList();

            categories = (from tc in ctx.TitleCategories
                          join c in ctx.Categories on tc.intCategory equals c.intId
                          select c).ToList();

            studios = (from ts in ctx.TitleStudios
                       join s in ctx.Studios on ts.intStudio equals s.intId
                       where ts.intTitle == title.intId
                       orderby ts.intSort
                       select s).ToList();

            if (title.intDirector.HasValue)
            {
                Person person = ctx.Persons.SingleOrDefault(p => p.intId == title.intDirector.Value);
                if (person != null)
                    Director = person.nvcName;
            }

            DirectoryInfo coverFolder = new DirectoryInfo(string.Format(@"\\{0}\MyMoviesFileStorage$\Covers", serverName));
            //if (coverFolder.Exists && !string.IsNullOrEmpty(title.Cover))
            //{
                FolderImage = Path.Combine(MovieDirectory, "folder.jpg");
                BackCover = Path.Combine(coverFolder.FullName, title.nvcCoverBack + ".jpg");
            //}


            CheckBoxItem.Value = MovieTitle.Watched;
            CheckBoxItem.PropertyChanged += new PropertyChangedEventHandler(CheckBoxItem_PropertyChanged);
            MovieTitle.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(title_PropertyChanged);            
        }

        void SpinnerItems_ChosenChanged(object sender, EventArgs e)
        {
            NumberOfTrailersToPlay = int.Parse(SpinnerItems.Chosen.ToString());
        }

        void title_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Watched")
            {
                MyMoviesBusiness.MarkMovieAsWatched(MovieTitle, MovieTitle.Watched);
            }
        }

        public void GetFiles()
        {
            Files = new List<MediaFile>();
            DirectoryInfo folder = new DirectoryInfo(MovieDirectory);
            if (folder.Exists)
            {
                DirectoryInfo dvdFolder = folder.GetDirectories("VIDEO_TS").FirstOrDefault();
                if (dvdFolder != null)
                {
                    Files.Add(new MediaFile() { FileName = "Watch", Path = dvdFolder.FullName });
                }

                List<FileInfo> _files = new List<FileInfo>();
                foreach (string ext in extensions)
                    _files.AddRange(folder.GetFiles(ext));
                if (_files.Count == 1)
                {
                    Files.Add(new MediaFile() { FileName = "Watch", Path = _files[0].FullName });
                }
                else
                {
                    foreach (FileInfo file in _files.OrderBy(f => f.Name))
                    {
                        Files.Add(new MediaFile() { FileName = file.Name, Path = file.FullName });
                    }
                }
            }
        }

        //public MyMovie(string movieDirectory)
        //    :base()
        //{
        //    //MovieDirectory = movieDirectory;

        //    //FileInfo xmlFile = new FileInfo(System.IO.Path.Combine(MovieDirectory, "mymovies.xml"));
        //    //if (xmlFile.Exists)
        //    //{
        //    //    XDocument doc = XDocument.Load(xmlFile.FullName);
        //    //    XElement xMovie = doc.Element("Title");
        //    //    if (xMovie != null)
        //    //        PopulateValues(xMovie);
        //    //    else
        //    //        PopulateValues();
        //    //}
        //    //else
        //    //    PopulateValues();

        //    //FolderImage = File.Exists(Path.Combine(MovieDirectory, "folder.jpg")) ? "file://" + Path.Combine(MovieDirectory, "folder.jpg") : "";
        //    //AddFiles();
        //}


        //public void ParseXml(string movieXml)
        //{
        //    //XDocument doc = XDocument.Parse(movieXml);
        //    //XElement xMovie = doc.Element("Title");
        //    //if (xMovie != null)
        //    //    PopulateValues(xMovie);
        //}
        //public void PopulateValues(XElement xMovie)
        //{
        //    //Title = xMovie.Element("OriginalTitle").Value;
        //    //SortTitle = xMovie.Element("SortTitle").Value;
        //    //if (string.IsNullOrEmpty(SortTitle))
        //    //    SortTitle = Title;
        //    //if (xMovie.Element("ReleaseDate") != null && !string.IsNullOrEmpty(xMovie.Element("ReleaseDate").Value))
        //    //    ReleaseDate = DateTime.Parse(xMovie.Element("ReleaseDate").Value);
        //    //Runtime = FormatRuntime(xMovie.Element("RunningTime").Value);
        //    //MovieDescription = xMovie.Element("Description").Value;
        //    //if (xMovie.Element("ParentalRating") != null)
        //    //{
        //    //    string r = xMovie.Element("ParentalRating").Element("Value") != null ? xMovie.Element("ParentalRating").Element("Value").Value : "";
        //    //    RatingDescription = xMovie.Element("ParentalRating").Element("Description") != null ? xMovie.Element("ParentalRating").Element("Description").Value : "";
        //    //    Rating = GetRating(r);
        //    //}

        //    //if (xMovie.Element("Covers") != null)
        //    //{
        //    //    if (xMovie.Element("Covers").Element("Front") != null)
        //    //        FrontCover = Path.Combine(MovieDirectory, xMovie.Element("Covers").Element("Front").Value);
        //    //    if (xMovie.Element("Covers").Element("Back") != null)
        //    //        BackCover = Path.Combine(MovieDirectory, xMovie.Element("Covers").Element("Back").Value);
        //    //}

        //    //if (xMovie.Element("Genres") != null && xMovie.Element("Genres").Element("Genre") != null)
        //    //    Genre = xMovie.Element("Genres").Element("Genre").Value;
        //    //if (xMovie.Element("Studios") != null && xMovie.Element("Studios").Element("Studio") != null)
        //    //    Studio = xMovie.Element("Studios").Element("Studio").Value;

        //    //var q2 = xMovie.Element("Persons").Descendants("Person").Where(p => p.Element("Type").Value == "Director");
        //    //if (q2.Count() > 0)
        //    //    Director = q2.First().Element("Name").Value;

        //    ////FolderImage = File.Exists(Path.Combine(MovieDirectory, "folder.jpg")) ? "file://" + Path.Combine(MovieDirectory, "folder.jpg") : "";

        //    //var q = from p in xMovie.Element("Persons").Descendants("Person")
        //    //        where p.Element("Name") != null && p.Element("Type") != null && p.Element("Role") != null && p.Element("Type").Value == "Actor"
        //    //        select new CastMember() { Name = p.Element("Name").Value, Type = p.Element("Type").Value, Role = p.Element("Role").Value };

        //    //Cast.AddRange(q);

        //    //foreach (CastMember member in Cast)
        //    //{
        //    //    if (!string.IsNullOrEmpty(member.Role))
        //    //        member.Name = string.Format("{0} - {1}", member.Name, member.Role);
        //    //}
        //}

        //private void AddFiles()
        //{            
        //    DirectoryInfo folder = new DirectoryInfo(MovieDirectory);
        //    List<FileInfo> _files = new List<FileInfo>();
        //    foreach(string ext in extensions)
        //        _files.AddRange(folder.GetFiles(ext));

        //    foreach (FileInfo file in _files.OrderBy(f => f.Name))
        //    {
        //        Files.Add(new MediaFile() { FileName = file.Name, Path = "file://" + file.FullName });
        //    }
        //}

        //private string FormatRuntime(string runtime)
        //{
        //    int x;
        //    if (int.TryParse(runtime, out x))
        //    {
        //        TimeSpan span = TimeSpan.FromMinutes(x);
        //        return string.Format("{0}:{1}", span.Hours, span.Minutes.ToString().PadLeft(2, '0'));
        //    }
        //    return runtime;
        //}

        //private string GetRating(string r)
        //{
        //    int x;
        //    if (int.TryParse(r, out x))
        //    {
        //        if (x <= 0)
        //            return "";
        //        string[] ratings = new string[] { "", "Not Rated", "G", "PG", "PG-13","", "R" };
        //        if (ratings.Length > x)
        //            return ratings[x];
        //    }
        //    return r;
        //}
    }
}
